<template>
  <div class="login-page">
    <h1 class="title">名厨亮灶</h1>
    <div class="login-box">
      <!-- 登录 -->
      <div class="logon" :class="{ hidden: !isLogin }">
        <h2>登录</h2>
        <el-form ref="loginForm" :model="loginFormData" label-width="50px" :rules="loginRules">
          <div class="form-container1">
            <el-form-item prop="username">
              <el-input v-model="loginFormData.username" placeholder="请输入用户名" clearable>
                <template v-slot:prepend> 用户名 </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model="loginFormData.password" type="password" clearable placeholder="请输入密码" show-password
                style="margin-top: 20px">
                <template v-slot:prepend> 密<span class="second-font">码</span> </template>
              </el-input>
            </el-form-item>
          </div>
          <div class="btn-gourp">
            <div>
              <el-checkbox class="remeber-password" v-model="checked"
                style="color: #a0a0a0; margin: 0 0 0px 0">记住密码</el-checkbox>
            </div>
            <div>
              <el-button :loading="loading" @keyup.enter="submitLoginForm" type="primary" plain
                @click="submitLoginForm">登录</el-button>
            </div>
          </div>
        </el-form>
      </div>
      <!-- 注册 -->
      <div class="register" :class="{ hidden: isLogin }">
        <h2>注册</h2>
        <el-form ref="registerForm" :model="registerFormData" label-width="50px" class="form-container" width="width"
          :rules="registerRules">
          <el-form-item prop="username">
            <el-input v-model="registerFormData.username" placeholder="请输入用户名" clearable>
              <template v-slot:prepend> 用户名 </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input v-model="registerFormData.email" placeholder="请输入邮箱" clearable>
              <template v-slot:prepend> 邮<span class="second-font">箱</span> </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="registerFormData.password" type="password" clearable placeholder="请输入密码" show-password>
              <template v-slot:prepend> 密<span class="second-font">码</span> </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input v-model="registerFormData.confirmPassword" type="password" clearable placeholder="请再次输入密码" show-password>
              <template v-slot:prepend> 确认密码 </template>
            </el-input>
          </el-form-item>
          <div class="btn-gourp">
            <div></div>
            <div>
              <el-button :loading="loading" @keyup.enter="submitRegisterForm" type="primary" plain
                @click="submitRegisterForm">注册</el-button>
            </div>
          </div>
        </el-form>
      </div>
      <!-- 左右移动的切换按钮 -->
      <div class="move" ref="moveRef">
        <span style="font-size: 18px; margin-bottom: 25px; color: rgb(225, 238, 250)">{{
          !isLogin ? '已有账号？' : '还没有账号？'
        }}</span>
        <span style="font-size: 16px; color: rgb(225, 238, 250)">{{
          !isLogin ? '欢迎登录账号！' : '欢迎注册账号！'
        }}</span>
        <el-button style="width: 100px; margin-top: 30px" @click="changeLogin">{{
          !isLogin ? '去登录' : '去注册'
        }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { login, getUserInfo, register } from '@/api/user'
import { Message } from 'element-ui'

export default {
  data() {
    return {
      // 登录表单数据
      loginFormData: {
        username: '',
        password: ''
      },
      // 注册表单数据
      registerFormData: {
        username: '',
        password: '',
        confirmPassword: '',
        email: ''
      },
      // 登录表单验证规则
      loginRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      },
      // 注册表单验证规则
      registerRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ]
      },
      loading: false,
      checked: true,
      isLogin: true
    }
  },
  methods: {
    // 登录表单提交
    submitLoginForm() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            // 使用 API 方法进行登录
            const response = await login(this.loginFormData)
            if (response && response.code === 1) {
              // 存储 token
              this.$store.commit('user/SET_TOKEN', response.data.token)
              // 获取用户信息
              const userInfoResponse = await getUserInfo()
              if (userInfoResponse && userInfoResponse.code === 1) {
                // 存储用户信息
                this.$store.commit('user/SET_USER_INFO', userInfoResponse.data)
                // 如果选择了记住密码，保存登录信息
                if (this.checked) {
                  localStorage.setItem('rememberedUser', JSON.stringify({
                    username: this.loginFormData.username,
                    password: this.loginFormData.password
                  }))
                } else {
                  localStorage.removeItem('rememberedUser')
                }
                Message.success((response && response.msg) || '登录成功')
                setTimeout(() => {
                  this.$router.push('/home')
                }, 1000)
              } else {
                Message.error((userInfoResponse && userInfoResponse.msg) || '获取用户信息失败')
              }
            } else {
              Message.error((response && response.msg) || '登录失败')
            }
          } catch (error) {
            console.error('登录错误:', error)
            Message.error('登录失败，请稍后重试')
          } finally {
            this.loading = false
          }
        }
      })
    },
    // 注册表单提交
    submitRegisterForm() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            await register({
              username: this.registerFormData.username,
              password: this.registerFormData.password,
              email: this.registerFormData.email
            })
            Message.success('注册成功')
            setTimeout(() => {
              this.isLogin = true
              this.$refs.moveRef.style.transform = 'translate(0, 0)'
            }, 1000)
          } catch (error) {
            console.error('注册错误:', error)
            Message.error('注册失败，请稍后重试')
          } finally {
            this.loading = false
          }
        }
      })
    },
    // 验证确认密码
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.registerFormData.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    // 切换登录/注册状态
    changeLogin() {
      this.isLogin = !this.isLogin
      if (this.isLogin) {
        this.$refs.moveRef.style.transform = 'translate(0, 0)'
      } else {
        this.$refs.moveRef.style.transform = 'translate(-420px, 0)'
      }
    }
  },
  mounted() {
    // 检查是否有保存的登录信息
    const rememberedUser = localStorage.getItem('rememberedUser')
    if (rememberedUser) {
      const { username, password } = JSON.parse(rememberedUser)
      this.loginFormData.username = username
      this.loginFormData.password = password
      this.checked = true
    }
  }
}
</script>

<style lang="less" scoped>
.login-page {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #ffffff;
}

.title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 15%;
  z-index: 999;
  font-size: 40px;
  color: #2d6a4f;
  font-weight: bolder;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.login-box {
  border: 2px solid #74c69d;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  border-radius: 20px;
  padding: 0 40px 0 40px;
  width: 700px;
  position: absolute;
  z-index: 999;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-sizing: border-box;
  box-shadow: 0 0 20px rgba(116, 198, 157, 0.2);
  background-color: #fff;
  animation: hideIndex 0.5s;

  h2 {
    font-size: 30px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #2d6a4f;
    width: 100%;
    text-align: center;
    padding: 20px;
  }

  .el-form-item {
    margin-bottom: 23px;
  }

  .btn-gourp {
    margin-top: 30px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .el-button {
      width: 100px;
      background-color: #74c69d;
      border-color: #74c69d;
      color: #ffffff;
      &:hover {
        background-color: #52b788;
        border-color: #52b788;
        color: #ffffff;
      }
    }

    .remeber-password {
      left: 0;
      line-height: 0.5rem;
      color: #40916c;
    }
  }

  .el-checkbox {
    width: 100%;
    text-align: center;
    margin-top: 1rem;
  }
}

/deep/ .el-form-item__content {
  margin-left: 0 !important;
}

/deep/ .el-input__inner {
  &:focus {
    border-color: #74c69d;
  }
}

/deep/ .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #74c69d;
  border-color: #74c69d;
}

/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #40916c;
}

@keyframes hideIndex {
  0% {
    opacity: 0;
    transform: translate(7.3125rem, -50%);
  }
  100% {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

.logon {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.hidden {
  animation: hidden 1s;
  animation-fill-mode: forwards;
}

@keyframes hidden {
  0% {
    opacity: 1;
  }
  70% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

.move {
  position: absolute;
  right: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 40%;
  transition-duration: 0.5s;
  align-items: center;
  background: linear-gradient(to right, #74c69d, #52b788);
  color: #fff;

  .el-button {
    background: transparent;
    border: 2px solid #fff;
    color: #ffffff;
    &:hover {
      background: #fff;
      color: #74c69d;
    }
  }
}

:deep(.el-input__suffix-inner) {
  width: 60px;
}

.form-container1 {
  transform: translateY(-80%);
}

.second-font {
  margin-left: 13px;
}
</style>